<template>
	<view>
		<view v-if='remains > 0' class="container">
			<view v-if='coupon.image' class='coupon'>
				<u-image width="100%" mode='widthFix' :src="coupon.image" border-radius='5px'></u-image>
			</view>
			<!-- <view v-else class='coupon-img'>
				<view>
					<view style='text-align:center;color:#606266;padding:10px 0px;'>《{{coupon.name}}》 </view>
					<view style='color:#9009399'>
						<view style='text-align:center'>使用规则</view>
						<view style='padding-top: 5px;'></view>
						<view style='padding-top: 5px;'></view>
						<view v-if='coupon && coupon.stores.length == 0'>所有门店通用</view>
						<view v-else>
							可用门店:<text v-for='s in coupon.stores'> {{s.__toString}} </text>
						</view>
						<view style='padding-top: 5px;'></view>
						<view style='padding-top: 15px;'></view>
					</view>
				</view>
			</view> -->
			<view style='padding:10px 30%'>
				<view class='remains'>
					<u-image width="100%" mode='widthFix'
						src="https://picture.jmgc.vip/335e40e3-a2e2-4b55-b35d-1700ecf0d050.png"
						border-radius='5px'></u-image>
					<text style='position: absolute;top:0px;left:25%'>当前剩余{{remains}}张</text>
				</view>
			</view>
			<view class='detail'>
				<view>《领券时间》</view>
				<view>
					{{$u.timeFormat(coupon.pickUpStartTime, 'yyyy年mm月dd日 hh:MM')}} 到
					{{$u.timeFormat(coupon.pickUpEndTime, 'yyyy年mm月dd日 hh:MM')}}
				</view>
			</view>
			<view v-if='canRob == 0' style='padding:10px 15%'>
				<u-button v-if="memberPhone == ''" size='large' type='success' open-type="getPhoneNumber"
					@getphonenumber="getPhoneNumber">马上领券</u-button>
				<u-button v-else type='success' size='large' @click='robCoupon'>马上领券</u-button>
			</view>
			<view v-if='canRob == 1' style='padding:10px 15%;'>
				<u-button type='error'>已结束</u-button>
			</view>
			<view v-if='canRob == -1' style='padding:10px 15%;'>
				<u-button type='default'>未开始</u-button>
			</view>
		</view>
		<view v-else class='noCoupon' @click='toIndex'>

		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				coupon: '',
				id: 0,
				remains: 1,
				title: '',
				sessionKey: '',
				memberPhone: '',
				canRob: 3
			}
		},
		onShow() {

		},
		onLoad(options) {
			console.log(options)
			if (typeof(options.scene) != 'undefined') {
				this.id = options.scene
				this.getCoupon()
			} else {
				uni.switchTab({
					url: '/pages/index/index'
				})
			}
		},
		onShareAppMessage() {
			return {
				title: this.coupon.name,
				imageUrl: this.coupon.image
			}
		},
		methods: {
			getCoupon() {
				if (this.id == 0) {
					uni.showModal({
						title: '很遗憾',
						content: '活动已结束',
						success: function(data) {
							uni.switchTab({
								url: '/pages/index/index'
							})
						}
					})
				}
				uni.showLoading({
					title: '正在获取优惠券'
				})
				//先判断登录状态
				let token = uni.getStorageSync('api_token')
				if (token == '') {
					this.wxLogin()
				} else {
					//获取用户信息
					this.request.get(`api/user`, {
						"@expands": "['entity.profile']"
					}).then((res) => {
						if (res.data.profile.__metadata.phone != null) {
							this.memberPhone = res.data.profile.__metadata.phone
						}
					})
					console.log('id', this.id)
					this.request.get(`api/coupons/${this.id}`).then((res) => {
						console.log('couponData', res)
						if (!res.data.isCollectAvailable) {
							uni.showModal({
								title: '',
								content: '该卡券不支持领取！',
								showCancel: false,
								success: (data) => {
									uni.switchTab({
										url: '/pages/index/index'
									})
								}
							})
						}
						this.remains = res.data.remains
						this.title = `当前剩余${res.data.remains}张`
						if (res.data.remains > 0) {
							this.coupon = res.data
							// 按时间判断判断是否可抢
							let now = new Date()
							let startTime = new Date(res.data.pickUpStartTime)
							let endTime = new Date(res.data.pickUpEndTime)
							if (now.getTime() > startTime.getTime() && now.getTime() < endTime.getTime()) {
								this.canRob = 0
							}
							if (now.getTime() < startTime.getTime()) {
								this.canRob = -1
							}
							if (now.getTime() > endTime.getTime()) {
								this.canRob = 1
							}
						}
						uni.hideLoading()
					}).catch((err) => {
						console.log(err)
					})
				}
			},
			getPhoneNumber(e) {
				let _this = this
				if (typeof(e.detail.iv) == 'undefined') {
					uni.showToast({
						title: '请先授权获取您的手机号码！',
						icon: 'none'
					})
					return
				} else {
					console.log('sessionKey', this.sessionKey)
					if (this.sessionKey != '') {
						let data = {
							sessionKey: this.sessionKey,
							iv: e.detail.iv,
							encryptedData: e.detail.encryptedData,
						}
						this.request.post(`wechat/decrypt-data`, data).then((res) => {
							console.log('phone', res);
							//更新手机号码
							this.request.put(`api/user-profile`, {
								phone: res.data.phoneNumber
							}).then((res) => {
								this.robCoupon()
							})
						})
					} else {
						uni.login({
							provider: "weixin",
							success: function(res) {
								let data = {
									code: res.code
								}
								_this.request.get("wechat/mini/login", data).then((res) => {
									if (res.data.data.session_key) {
										let data = {
											sessionKey: res.data.data.session_key,
											iv: e.detail.iv,
											encryptedData: e.detail.encryptedData,
										}
										_this.request.post(`wechat/decrypt-data`, data).then((res) => {
											console.log('phone', res);
											//更新手机号码
											_this.request.put(`api/user-profile`, {
												phone: res.data.phoneNumber
											}).then((res) => {
												_this.robCoupon()
											})
										})
									} else {
										uni.showToast({
											title: '获取手机号码失败！',
											icon: 'none'
										})
									}
								})
							},
						});
					}

				}
			},
			robCoupon() {
				if(this.coupon.requirePoints > 0){
					uni.showModal({
						title: '提示',
						content: `是否使用${this.coupon.requirePoints}进行兑换？`,
						success: (data) => {
							if(data.confirm){
								this.pay()
							}
						}
					})
				}else{
					this.pay()
				}
			},
			pay(){
				uni.showLoading()
				this.request.post(`api/user-coupons`, {
					coupon: this.coupon.id
				}).then((res) => {
					console.log(res)
					let userCouponId = res.data.id
					uni.hideLoading()
					uni.showModal({
						title: '恭喜您！',
						content: '成功抢到了优惠券\n快去小程序使用下单吧',
						showCancel: false,
						confirmText: '查看券包',
						success: () => {
							uni.redirectTo({
								url: '/pages/mine/coupon'
							})
						}
					})
				}).catch(() => {
					uni.showModal({
						title: '',
						content: '积分余额不足或不满足领取条件',
						showCancel: false,
						success: () => {}
					})
					uni.hideLoading()
				})
			},
			wxLogin() {
				let _this = this;
				uni.login({
					provider: "weixin",
					success: function(res) {
						let data = {
							code: res.code
						}
						_this.request.get("wechat/mini/login", data).then((res) => {
							console.log('loginData', res)
							if (res.data.token) {
								uni.setStorageSync('api_token', res.data.token)
								_this.getCoupon()
							}
							if (res.data.data.session_key) {
								_this.sessionKey = res.data.data.session_key
							}
						})
					},
				});
			},
			toIndex() {
				uni.switchTab({
					url: '/pages/index/index'
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		height: 100vh;
		padding-top: 20px;
		width: 100%;
		background-image: url('https://picture.jmgc.vip/7b7085a1-74f6-4a81-a035-7e7ab5d0d85e.png');
		background-size: 100%;
	}

	.noCoupon {
		height: 100vh;
		width: 100%;
		background-image: url('https://picture.jmgc.vip/7b868e2b-c244-487d-b4b2-94be3d0eece0.png');
		background-size: 100%;
	}

	.remains {
		width: 100%;
		color: white;
		line-height: 40px;
		height: 40px;
		margin-bottom: -40px;
		position: relative;
	}

	.coupon {
		padding: 10px 10px 0px 10px;
	}

	.detail {
		background-color: #207F32;
		border: solid #95C134 3px;
		margin: 10px;
		padding: 25px 10px 10px 10px;
		font-size: 12px;
		text-align: center;
		color: white;
		border-radius: 0px 0px 35px 35px;

	}

	.coupon-img {
		// background-color: white;
		color: #909399;
		padding: 20px 10%;
		background-image: url('https://picture.jmgc.vip/be79ecb8-548f-40e0-a235-ea3ab5259141.png');
		background-size: 100% 100%;
	}
</style>